package com.hschinese.pronunciation.activity;


import android.app.Activity;
import android.app.Application;
import android.content.Context;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.utils.Constant;
import com.hschinese.pronunciation.utils.UserInfoUtil;
import com.hschinese.pronunciation.utils.Utils;
import com.iflytek.cloud.SpeechUtility;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.model.HttpParams;
import com.mob.MobSDK;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

//import com.tendcloud.tenddata.TCAgent;

public class MyApplication extends Application {
	private static MyApplication application = null;
	private String uid = null;
	private int isGuest = -1;
	private LinkedList<Activity> allAtys;
	private String language = null;
	private boolean isShow = false;

	@Override
	public void onCreate() {
		super.onCreate();
		// 科大讯飞的语音识别的初始化（AppID）
		SpeechUtility.createUtility(MyApplication.this, "appid=" + getString(R.string.app_kdxf_id));
//		TCAgent.init(this.getApplicationContext());
//		TCAgent.setReportUncaughtExceptions(false);

		MobSDK.init(this);
		application = this;
		initAty();
		initOkGo();
	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
	}

	public static MyApplication getInstance() {
		if (null == application) {
			synchronized (MyApplication.class) {
				if (null == application) {
					application = new MyApplication();
				}
			}
		}
		return application;
	}

	public boolean isShow() {
		return isShow;
	}

	public String getUid() {
		if (null == uid) {
			uid = UserInfoUtil.getInstance(this).getUid();
		}
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public int getIsGuest() {
		if (-1 == isGuest) {
			isGuest = UserInfoUtil.getInstance(this).getIsGuest();
		}
		return isGuest;
	}

	public void setIsGuest(int isGuest) {
		this.isGuest = isGuest;
	}

	public void setShow(boolean isShow) {
		this.isShow = isShow;
	}

	private void initAty() {
		allAtys = new LinkedList<Activity>();

	}
	public void pushAty(Activity aty) {
		this.allAtys.addLast(aty);
	}

	public LinkedList<Activity> getAllAtys() {
		return allAtys;
	}

	public Activity pollAty() {
		if (this.allAtys.size() == 0) {
			return null;
		}
		return this.allAtys.getLast();
	}

	@SuppressWarnings("rawtypes")
	public Activity getActivityByClass(Class clazz) {
		for (Activity aty : allAtys) {
			if (aty.getClass().equals(clazz)) {
				return aty;
			}
		}
		return null;
	}

	public void removeAndFinish(Class... clazzs) {
		for (int i = 0; i < clazzs.length; i++) {
			Activity aty = getActivityByClass(clazzs[i]);
			if (aty == null) {
				continue;
			}
			this.allAtys.remove(aty);
			aty.finish();
		}
	}

	public boolean removeAty(Activity aty) {
		Activity ac = pollAty();
		if (null != ac && ac.equals(aty)) {
			this.allAtys.remove(aty);
			return true;
		}
		return false;
	}

	public String getLanguage() {
		if (null == language) {
			language = Utils.getLanguage(this);
			language = Constant.LANGUAGE_CHINESE.equals(language)?"zh-hans":language;
		}
		return language;
	}

	public OkHttpClient getOkHttpClient(int requestTimeoutShort, int soTimeoutShort) {
		OkHttpClient client = new OkHttpClient();
		/*client.setConnectTimeout(requestTimeoutShort, TimeUnit.MILLISECONDS);
		client.setReadTimeout(requestTimeoutShort, TimeUnit.MILLISECONDS);
		client.setWriteTimeout(requestTimeoutShort, TimeUnit.MILLISECONDS);*/

		return client;
	}



	



	private void initOkGo() {
		//---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//

      /*  headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文，不允许有特殊字符
        headers.put("commonHeaderKey2", "commonHeaderValue2");*/
		HttpParams params = new HttpParams();
		params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
		params.put("commonParamsKey2", "这里支持中文参数");
		//----------------------------------------------------------------------------------------//

		OkHttpClient.Builder builder = new OkHttpClient.Builder();
		//添加OkGo默认debug日志
		//超时时间设置，默认60秒
		builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
		builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
		builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

		//自动管理cookie（或者叫session的保持），以下几种任选其一就行
		//builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效
		builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));              //使用数据库保持cookie，如果cookie不过期，则一直有效
		//builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie，app退出后，cookie消失
		// 其他统一的配置
		// 详细说明看GitHub文档：https://github.com/jeasonlzy/
		OkGo.getInstance().init(this)                           //必须调用初始化
				.setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
				.setCacheMode(CacheMode.NO_CACHE)   //全局统一缓存模式，默认不使用缓存，可以不传
				.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
				//全局统一缓存时间，默认永不过期，可以不传
				.setRetryCount(3)//全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
		;                    //全局公共头
		//  .addCommonParams(params);                      //全局公共参数
	}
}
